<template>
  <div>
    <my-breadcrumb :items="['系统管理', '广告页']"/>
    <!-- <search :formItems="searchItems" @search='getList' ref='search'/> -->
    <div class="add">
      <el-button type="primary" @click="toAdd">新增广告页</el-button>
    </div>
    <el-table :data="banners">
      <el-table-column
        type="index"
        width="55">
      </el-table-column>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createtime">
      </el-table-column>
      <el-table-column
        label="发布时间"
        prop="updatetime">
      </el-table-column>
      <el-table-column
        label="标题"
        prop="title">
      </el-table-column>
      <el-table-column
        label="展示时间"
        prop="showtime">
      </el-table-column>
      <el-table-column
        label="展示顺位"
        prop="orderby">
      </el-table-column>
      <el-table-column
        label="图片"
        prop="img">
        <template slot-scope="scope">
          <img :src="scope.row.img" alt="" height="40">
        </template>
      </el-table-column>
      <el-table-column
        label="广告页状态"
        prop="status">
        <template slot-scope="scope">
          {{ scope.row.status === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        prop="id">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="toDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="isAdd ? '新增广告页' : '信息修改'" :visible.sync="showAdd">
      <el-form :model="banner" :rules="rules" label-width="90px" ref="addForm">
        <el-form-item label="类型" prop="jumptype">
          <el-select v-model="banner.jumptype" @change="showRich">
            <el-option value="1" label="资讯"/>
            <el-option value="2" label="帖子"/>
            <el-option value="3" label="闲置"/>
            <el-option value="4" label="repo"/>
            <el-option value="5" label="富文本"/>
            <el-option value="6" label="链接"/>
            <el-option value="7" label="抽奖"/>
            <el-option value="8" label="求购"/>
            <el-option value="9" label="发现帖子"/>
          </el-select>
        </el-form-item>
        <el-form-item label="选择资讯" prop="jumpid" v-if="banner.jumptype === '1'">
          <div class="select-box">
            <img :src="selectNow.img1" alt="" width="40px" v-show="selectNow.img1">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectNew')">{{ selectNow.title ? '重新选择资讯' : '选择资讯' }}</el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择帖子" prop="jumpid" v-if="banner.jumptype === '2'">
          <div class="select-box">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectTopic')">{{ selectNow.title ? '重新选择帖子' : '选择帖子' }}</el-button>
          </div>
        </el-form-item>

        <el-form-item label="发现帖子" prop="jumpid" v-if="banner.jumptype === '9'">
          <div class="select-box">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectRich')">{{ selectNow.title ? '重新选择帖子' : '选择帖子' }}</el-button>
          </div>
        </el-form-item>

        <el-form-item label="选择闲置" prop="jumpid" v-if="banner.jumptype === '3'">
          <div class="select-box">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectShop')">{{ selectNow.title ? '重新选择闲置' : '选择闲置' }}</el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择求购" prop="jumpid" v-if="banner.jumptype === '8'">
          <div class="select-box">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectShop2')">{{ selectNow.title ? '重新选择求购' : '选择求购' }}</el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择repo" prop="jumpid" v-if="banner.jumptype === '4'">
          <div class="select-box">
            <span style="margin: 0 20px 0 12px;" v-show="selectNow.title">{{ selectNow.title }}</span>
            <el-button type="text" @click="toSelect('selectRepo')">{{ selectNow.title ? '重新选择repo' : '选择repo' }}</el-button>
          </div>
        </el-form-item>

        <el-form-item label="链接" prop="link" v-if="banner.jumptype === '6'">
          <el-input v-model="banner.link"/>
        </el-form-item>
        <el-form-item label="富文本" :prop="banner.jumptype === '5' ? 'content' : ''" v-show="banner.jumptype === '5'">
          <div id="navBar" class="navBar"></div>
          <div id="editor"></div>
        </el-form-item>

        <el-form-item label="是否启用" prop="status">
          <el-select v-model="banner.status">
            <el-option value="1" label="是"/>
            <el-option value="0" label="否"/>
          </el-select>
        </el-form-item>

        <el-form-item label="展示时间" prop="showtime">
          <el-input-number v-model="banner.showtime" :min="0"/>
        </el-form-item>

        <el-form-item label="展示顺位" prop="orderby">
          <el-input-number v-model="banner.orderby" :min="0"/>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload">
            <img v-if="banner.img" :src="banner.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="primary" @click="toSubmit">提交</el-button>
        <el-button type="danger" @click="showAdd = false">取消</el-button>
      </div>
    </el-dialog>
    <select-list ref="selectNew" :url="'/placard/index?delflag=0'" :searchItems="newSearch" :tableItem="newTableItems" @selectRow="nowChange"/>
    <select-list ref="selectTopic" :url="'/article/index?delflag=0'" :searchItems="topicSearch" :tableItem="topicTableItems" @selectRow="nowChange"/>
    <select-list ref="selectRich" :url="'/Richarticle/index?delflag=0'" :searchItems="topicSearch" :tableItem="topicTableItems" @selectRow="nowChange"/>
    <select-list ref="selectRepo" :url="'/repo/index?delflag=0'" :searchItems="repoSearch" :tableItem="repoTableItems" @selectRow="nowChange"/>
    <select-list ref="selectShop" :url="'/Used/index?delflag=0&addtype=1'" :searchItems="shopSearch" :tableItem="shopTableItems" @selectRow="nowChange"/>
    <select-list ref="selectShop2" :url="'/Used/index?delflag=0&addtype=2'" :searchItems="shopSearch" :tableItem="shopTableItems" @selectRow="nowChange"/>
  </div>
</template>

<script>
import {deleteRow} from '../../utils/getList'
import selectList from '@/components/common/selectList'
import tableItems from '@/config/tableItems'
const E = require('wangeditor')
export default {
  name: 'ad',
  data () {
    return {
      searchItems: [
        {
          label: '展示时间',
          type: 'input',
          key: 'showtime'
        },
        {
          label: '展示顺位',
          type: 'input',
          key: 'orderby'
        },
        {
          label: '广告页状态',
          type: 'select',
          key: 'status',
          options: [{ id: '0', name: '否' }, { id: '1', name: '是' }],
          width: '100'
        }
      ], // 检索结构
      newSearch: [
        {
          label: '标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '商品名称',
          type: 'input',
          key: 'name'
        }
      ],
      topicSearch: [
        {
          label: '帖子标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '发布人',
          type: 'input',
          key: 'membername'
        }
      ],
      repoSearch: [
        {
          label: '标题',
          type: 'input',
          key: 'title'
        }
      ],
      shopSearch: [
        {
          label: '标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '商品名称',
          type: 'input',
          key: 'skirtname'
        },
        {
          label: '发布人',
          type: 'input',
          key: 'membername'
        }
      ],
      banners: [],
      showAdd: false,
      isAdd: true,
      banner: {
        status: '1',
        showtime: 0,
        img: '',
        link: '',
        jumpid: '',
        jumptype: '',
        content: '',
        orderby: 0
      },
      rules: {
        img: [
          { required: true, message: '请选择图片', trigger: 'change' }
        ],
        link: [
          { required: true, message: '请填写超链接地址', trigger: 'blur' }
        ],
        jumpid: [
          { required: true, message: '请选择对应内容', trigger: 'change' }
        ],
        jumptype: [
          { required: true, message: '请选择轮播类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请编辑富文本内容', trigger: 'blur' }
        ],
        orderby: [
          { required: true, message: '请填写轮播图顺位', trigger: 'blur' }
        ]
      },
      updateRow: null,
      type: [
        {id: '1', name: '资讯'},
        {id: '2', name: '帖子'},
        {id: '3', name: '闲置'},
        {id: '4', name: 'repo'},
        {id: '5', name: '富文本'},
        {id: '6', name: '链接'},
        {id: '7', name: '抽奖'},
        {id: '8', name: '求购'},
        {id: '9', name: '发现帖子'}
      ],
      selectNow: {},
      richTableItems: tableItems.richList,
      newTableItems: tableItems.newList,
      topicTableItems: tableItems.postList,
      repoTableItems: tableItems.repoList,
      shopTableItems: tableItems.shopList,
      editor: null
    }
  },
  methods: {
    getList () {
      let searchData = {}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      let params = {
        ...searchData
      }
      this.axios.get('/Config/getadvertisement', {params})
        .then(res => {
          this.banners = res.data.data.list
        })
    },

    beforeUpload (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.banner.img = ev.currentTarget.result
      }
      reader.readAsDataURL(file)
      return false
    },

    toAdd () {
      this.isAdd = true
      this.showAdd = true
      this.selectNow = {}
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
      })
    },
    toUpdate (row) {
      this.isAdd = false
      this.showAdd = true
      this.updateRow = row
      this.selectNow = {}
      // console.log(row)
      this.selectNow.title = row.title
      this.$nextTick(() => {
        Object.keys(this.banner).forEach(key => {
          this.banner[key] = row[key]
        })
        if (row.jumptype === '5' && this.editor === null) {
          this.initEditor()
        }
        if (row.jumptype === '5') {
          this.editor.txt.html(row.content)
        }
      })
    },
    toSubmit () {
      let url = '/Config/addadvertisement'
      let params = {
        img: '',
        status: '',
        jumptype: '',
        jumpid: '',
        orderby: 0
      }
      Object.keys(params).forEach(key => {
        params[key] = this.banner[key]
      })
      if (params.jumptype === '1') {
        // params.jumpid = this.banner.newsid
        params.jumpid = this.banner.jumpid
      } else if (params.jumptype === '2') {
        params.jumpid = this.banner.jumpid
      } else if (params.jumptype === '4') {
        // params.jumpid = this.banner.repoid
        params.jumpid = this.banner.jumpid
      } else if (params.jumptype === '5') {
        params.content = this.banner.content
      } else if (params.jumptype === '6') {
        params.link = this.banner.link
      }
      if (!this.isAdd) {
        url = '/Config/editadvertisement'
        params.id = this.updateRow.id
      }
      params.showtime = this.banner.showtime
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.axios.post(url, this.qs.stringify(params))
            .then(res => {
              if (res.data.status === 1) {
                this.getList()
                this.$message.success(res.data.msg)
                this.showAdd = false
              }
            })
        } else {
          this.$message.error('请检查表单是否填写正确')
          return false
        }
      })
    },
    toDelete (id) {
      deleteRow({url: '/Config/deladvertisement', id}, res => {
        if (res.data.status === '1' || res.data.status === 1) {
          this.getList()
          this.$message.success(res.data.msg)
        }
      })
    },

    toSelect (ref) {
      this.$refs[ref].toShow()
      this.selectNow = {}
      this.banner.jumpid = ''
    },
    nowChange (row) {
      this.selectNow = row
      this.banner.jumpid = row.id
    },
    showRich (val) {
      if (val === '5' && this.editor === null) {
        this.$nextTick(() => {
          this.initEditor()
        })
      }
      // this.$nextTick(() => {
      //   if (val === '5' && this.editor === null) {
      //     this.initEditor()
      //   }
      // })
    },
    initEditor () {
      let _self = this
      let editor = new E('#navBar', '#editor')
      editor.customConfig.uploadImgServer = '/upload' // 图片上传路径
      editor.customConfig.showLinkImg = false // 隐藏网络图片tab
      editor.customConfig.uploadImgMaxSize = 20 * 1024 * 1024 // 设置大小
      // 图片上传错误时提醒
      editor.customConfig.customAlert = function (info) {
        // info 是需要提示的内容
        _self.$message.error(info)
      }
      editor.customConfig.customUploadImg = function (files, insert) {
        // files 是 input 中选中的文件列表
        // insert 是获取图片 url 后，插入到编辑器的方法

        // 上传代码返回结果之后，将图片插入到编辑器中
        files.forEach((item, index) => {
          _self.uploadImg(item, insert)
        })
      }
      editor.customConfig.onchange = function (html) {
        // 监控变化，同步更新到 textarea
        _self.banner.content = html
        _self.$emit('input', _self.banner.content)
      }
      // 菜单栏配置
      editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        'table', // 表格
        'undo', // 撤销
        'redo' // 重复
      ]
      editor.create()
      this.editor = editor
    },
    uploadImg (e, fn) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.axios.post('/oss/saveimg', _self.qs.stringify({imgarr: ev.currentTarget.result}))
          .then(res => {
            if (res.data.status === 1) {
              // _self.editor.txt.append(`<img src="${res.data.data.img}" max-width="100%">`)
              fn(res.data.data.img)
            }
          })
      }
      reader.readAsDataURL(e)
    }
  },
  components: {
    selectList
  },
  created () {
    this.getList()
  }
}
</script>

<style scoped>
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .select-box{
    display: flex;
    align-items: center;
  }
</style>
